package org.fusionide.builder.parsers.cfml.tags;

import java.util.Vector;

import org.fusionide.builder.parsers.IParserHandler;
import org.fusionide.builder.parsers.ParserException;
import org.fusionide.builder.parsers.cfml.CFMLTag;
import org.fusionide.builder.parsers.cfml.Variable;
import org.fusionide.util.RegEx;

public class Set extends CFMLTag {

	private static final String setVarPattern = "(var\\s+|)([\\w.]+?)(\\[.*?\\])?\\s*=\\s*([^\\s].*)";// "(var\\s+|)([\\w.\\[\\]]+?)\\s*=\\s*(.+)";

	private static final String createObjectPattern = "createobject\\s*\\(\\s*\"\\w+\"\\s*,\\s*\"(.+?)\"\\)";

	private static final String setAttributePattern = "([\\w.\\[\\]]+\\(.*?\\))|" + setVarPattern;

	public Set(String attributes, int startOffset) {
		super(attributes, startOffset);
	}

	public static void main(String[] args) {
		RegEx setRegex = RegEx.Compile("(var\\s+|)([\\w.]+?)(\\[.*?\\])?\\s*=\\s*([^\\s].*)", "i").match("var test[gay] = lksdjlfj");
		while (setRegex.next()) {
			for (int i = 0; i <= setRegex.getGroupCount(); i++) {
				System.out.println(setRegex.group(i));
			}
		}
	}

	@Override
	public boolean requiresClosingTag() {
		return false;
	}

	@Override
	public boolean acceptsChildren(CFMLTag tag) {
		return false;
	}

	@Override
	public Vector<Variable> getVariables(int offset) {
		Vector<Variable> vars = new Vector<Variable>();
		if (offset < endOffset)
			return vars;
		RegEx setRegex = RegEx.Compile(setVarPattern, "i").match(attributes);
		if (setRegex.next()) {
			boolean varScoped = true;

			if (hasParent(Function.class))
				if (setRegex.group(1).equalsIgnoreCase(""))
					varScoped = false;

			Variable var = new Variable(setRegex.group(2), startLine, varScoped);

			RegEx createObjectRx = RegEx.Compile(createObjectPattern, "i").match(setRegex.group(4));
			if (createObjectRx.next())
				var.setHint(createObjectRx.group(1));
			else
				var.setHint(setRegex.group(4));
			vars.add(var);
		}
		return vars;
	}

	@Override
	public boolean validate(IParserHandler parserHandler) {
		if (super.validate(parserHandler)) {
			if (attributes.equalsIgnoreCase("") && parserHandler != null)
				parserHandler.addMarker(new ParserException("<cfset> Requires a command", ParserException.SEVERITY_ERROR, startLine));

			if (!attributes.equalsIgnoreCase("") && !RegEx.Compile(setAttributePattern, "i").match(attributes).isMatched() && parserHandler != null)
				parserHandler.addMarker(new ParserException("<cfset> Malformed Set tag", ParserException.SEVERITY_ERROR, startLine));
			return true;
		}
		return false;
	}

}
